package cn.flying.cloud.task.core.handler;

import javax.annotation.Resource;

import java.time.LocalDateTime;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.flying.cloud.task.core.model.JobContext;
import cn.flying.cloud.task.core.quartz.enums.JobExecuteStatusEnum;
import cn.flying.cloud.task.core.quartz.exception.TaskException;
import cn.flying.cloud.task.entity.TaskJobLog;
import cn.flying.cloud.task.service.TaskJobLogService;

/**
 * @author: admin
 * @date: 2025年03月12日 23:54
 * @version: 1.0
 */
public abstract class AbstractJobHandler {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TaskJobLogService taskJobLogService;

    /**
     * 执行的抽象方法
     */
    public void executeJob(JobContext context) {
        TaskJobLog log = taskJobLogService.getObjById(context.getLogId());
        if (log == null) {
            log = new TaskJobLog();
        }
        log.setId(context.getLogId());
        log.setJobName(context.getJobName());
        log.setJobGroup(context.getJobGroup());
        log.setJobDesc(context.getJobDesc());
//        result.setStartTime(LocalDateTime.now());
        log.setTenantId(context.getTenantId());

        try {
            log.setFireTime(LocalDateTime.now());
            execute(context);
            // 执行成功
            log.setJobStatus("SUCCESS");
            log.setJobMsg("执行成功");
        } catch (Exception e) {
            logger.error("任务执行失败！", e);
            // 执行失败
            log.setJobStatus("FAIL");
            log.setJobMsg(e.getMessage());
            log.setJobTrace(ExceptionUtils.getStackTrace(e));
        } finally {
            // TODO
            log.setEndTime(LocalDateTime.now());
            taskJobLogService.updateObj(log);

            // 执行失败告警通知
            if (JobExecuteStatusEnum.FAIL.getCode().equals(log.getJobStatus())) {
                // TODO
            }
        }
    }

    /**
     * 执行
     */
    public abstract void execute(JobContext jobContext) throws TaskException;
}
